//
//  libCommon.m
//  lib
//

//
#import <QuartzCore/QuartzCore.h>
#import "libCommon.h"
#import "libAppViewController.h"
#import "libReplaceAnimation.h"



@implementation PointObj
@end



BOOL  IS_FIRST_LOAD = NO;
BOOL  SHOULD_RELOAD_MAIN = YES;	
BOOL  SHOULD_RELOAD_NEWS = YES;

BOOL  IS_IPAD = NO;
BOOL  IS_IPHONE4 = NO;
BOOL  IS_PAPERBACK = NO;

float DISPLAY_FULL_WIDTH = 320.0f;
float DISPLAY_FULL_HEIGHT = 480.0f;

CGRect			DISPLAY_RECT_PORT;
CGRect			DISPLAY_RECT_LAND;

CGRect			TOOLBAR_RECT_PORT;
CGRect			TOOLBAR_RECT_LAND;

CGRect			TABBAR_RECT_PORT;
CGRect			TABBAR_RECT_LAND;



void initRectFromDevice( void )
{
	CGRect rect = [[UIScreen mainScreen]bounds];
	
	DISPLAY_FULL_WIDTH = rect.size.width;
	DISPLAY_FULL_HEIGHT = rect.size.height;

	{
		
		UIDevice* dev = [UIDevice currentDevice];

		if([dev.model compare:@"iPhone"] == NSOrderedSame || [dev.model compare:@"iPod touch"] == NSOrderedSame){
			IS_IPAD = NO;
		}
		else if([dev.model compare:@"iPhone Simulator"] == NSOrderedSame){
			IS_IPAD = NO;
		}
		else if([dev.model compare:@"iPad Simulator"] == NSOrderedSame){
			IS_IPAD = YES;
		}
		else if([dev.model compare:@"iPad"] == NSOrderedSame){
			IS_IPAD = YES;
		}
		else{
			IS_IPAD = NO;
		}
		
		if(!IS_IPAD && [UIScreen instancesRespondToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0)
		{
			IS_IPHONE4 = YES;
		}
		
#ifdef TARGET_DEVICE_iPhone
		
		IS_IPAD = NO;
#elif defined TARGET_DEVICE_iPad
		
		IS_IPAD = YES;
#endif

		DebLog(@"%@, IS_IPAD=%d, IS_IPHONE4=%d", dev.model, IS_IPAD, IS_IPHONE4);
	}
	
	DISPLAY_RECT_PORT	= CGRectMake(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT);
	DISPLAY_RECT_LAND	= CGRectMake(0, 0, (DISPLAY_FULL_HEIGHT), (DISPLAY_WIDTH-CLOCK_HEIGHT));
	
	TOOLBAR_RECT_PORT	= CGRectMake(0, (DISPLAY_HEIGHT-TOOLBAR_HEIGHT), DISPLAY_WIDTH, TOOLBAR_HEIGHT);
	TOOLBAR_RECT_LAND	= CGRectMake(0, (DISPLAY_WIDTH-TOOLBAR_HEIGHT-CLOCK_HEIGHT),
									 (DISPLAY_FULL_HEIGHT), TOOLBAR_HEIGHT);
	
	TABBAR_RECT_PORT	= CGRectMake(0, (DISPLAY_HEIGHT-TABBAR_HEIGHT), DISPLAY_WIDTH, TABBAR_HEIGHT);
	TABBAR_RECT_LAND	= CGRectMake(0, (DISPLAY_WIDTH-TABBAR_HEIGHT-CLOCK_HEIGHT),
									 (DISPLAY_FULL_HEIGHT), TABBAR_HEIGHT);
}


CGRect getDispRectFromDevice( void )
{
	return getDispRect([libAppViewController Shared].m_DeviceOrie);
}

CGRect getBarRectFromDevice( void )
{
	if( isDeviceLandScape([libAppViewController Shared].m_DeviceOrie) )
		return TOOLBAR_RECT_LAND;
	return TOOLBAR_RECT_PORT;
}

void resizeViewFromDevice( UIView *view )
{
	view.frame = getDispRectFromDevice();
}


CGRect getAspectRect( CGRect rect, CGRect base_rect )
{
	float scaleX = base_rect.size.width / rect.size.width;
	float scaleY = base_rect.size.height / rect.size.height;
	if( scaleX > scaleY )	scaleX = scaleY;
	else					scaleY = scaleX;
	
	rect.size.width *= scaleX;
	rect.size.height *= scaleY;
	rect.origin.x = (base_rect.size.width - rect.size.width) / 2;
	rect.origin.y = (base_rect.size.height - rect.size.height) / 2;
	return rect;
}



CGRect createRect( CGPoint center, CGFloat width, CGFloat height )
{
	return CGRectMake((center.x - (width/2)), (center.y - (height/2)), width, height);
}



BOOL isInsidePointOnRect( CGRect rect, CGPoint check_pt )
{
	BOOL ret = NO;
	
	if( (rect.origin.x <= check_pt.x)
	   && ((rect.origin.x+rect.size.width) >= check_pt.x)
	   && (rect.origin.y <= check_pt.y)
	   && ((rect.origin.y+rect.size.height) >= check_pt.y)
	   )
	{
		ret = YES;
	}
	return ret;
}



BOOL isInsideRectOnRect( CGRect rect1, CGRect rect2 )
{
	BOOL ret = YES;
	
	
	if( (rect1.origin.x > (rect2.origin.x+rect2.size.width))
	   || (rect2.origin.x > (rect1.origin.x+rect1.size.width))
	   || (rect1.origin.y > (rect2.origin.y+rect2.size.height))
	   || (rect2.origin.y > (rect1.origin.y+rect1.size.height))
	   )
	{
		ret = NO;
	}
	return ret;
}



BOOL isPointOnPolygon( PointObj* p, NSArray* poly )
{
	int ct = [poly count];
	int ret = 0;
	
	// 0-1, 1-2, 2-3, 3-0
	for( int i=0; i<ct; ++i )
	{
		PointObj* p0 = (PointObj*)[poly objectAtIndex:i%ct];
		PointObj* p1 = (PointObj*)[poly objectAtIndex:(i+1)%ct];
		
		float rx = p->x - p0->x;
		float nx = p->x - p1->x;
		
		if( ( rx < 0 && nx >= 0) || (rx >= 0 && nx < 0) )
		{
			float ry = p->y - p0->y;
			float dx = p1->x - p0->x;
			float dy = p1->y - p0->y;
			
			if( rx * dy < ry * dx )
				++ret;
			else
				--ret;
		}
		
	}
	return ret;
}



double getLength( CGPoint p1, CGPoint p2 )
{
	double ret = sqrt(
					  ((p2.x - p1.x) * (p2.x - p1.x))
					  + ((p2.y - p1.y) * (p2.y - p1.y))
					  );
	return ret;
}



CGPoint getCenterPos( CGPoint p1, CGPoint p2 )
{
	CGPoint ret = {0.0f};
	ret.x = ((p1.x + p2.x) / 2.0f);
	ret.y = ((p1.y + p2.y) / 2.0f);
	
	return ret;
}


CGRect getDispRect( UIDeviceOrientation orie )
{
	if( isDeviceLandScape(orie) )
		return DISPLAY_RECT_LAND;
	return DISPLAY_RECT_PORT;
}
CGRect getToolBarRect( UIDeviceOrientation orie )
{
	if( isDeviceLandScape(orie) )
		return TOOLBAR_RECT_LAND;
	return TOOLBAR_RECT_PORT;
}

CGRect getTabBarRect( UIDeviceOrientation orie )
{
	if( isDeviceLandScape(orie) )
		return TABBAR_RECT_LAND;
	return TABBAR_RECT_PORT;
}



void setCAAnimation( UIView* view, NSString* type, NSString* sub_type, CGFloat duration )
{
	setCAAnimation2( view, type, sub_type, duration, view );
}
void setCAAnimation2( UIView* view, NSString* type, NSString* sub_type, CGFloat duration, id delegate )
{
	CATransition *anime = [CATransition animation];
	[anime setDelegate:delegate];
	
	[anime setType:type];
	[anime setSubtype:sub_type];
	
	[anime setDuration:duration];
	[anime setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
	
	
	[[view layer] addAnimation:anime forKey:kCATransition];
}



void setUIViewAnimation( UIView* view, UIViewAnimationTransition trans_type, CGFloat duration )
{
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:duration];
	[UIView setAnimationTransition:trans_type forView:view cache:YES];
	
	[UIView commitAnimations];
}



int searchViewOnView( UIView* on_view, UIView* search_view )
{
	int ret = -1;
	
	if( (on_view == nil) || (search_view == nil) ) return ret;
	
	int sub_num = [on_view.subviews count];
	int i;
	for( i=0; i<sub_num; i++ )
	{
		UIView *chk_view = [on_view.subviews objectAtIndex:i];
		if( chk_view == search_view ) break;
	}
	if( i < sub_num ) { ret = i; }
	
	return ret;
}

BOOL isViewOnView( UIView* on_view, UIView* search_view )
{
	return (( on_view )&&( search_view.superview == on_view ));
}



int removeViewOnView( UIView* on_view, UIView* del_view )
{
	int ret = searchViewOnView( on_view, del_view );
	if( ret != -1 )
	{
		
		UIView* view = [on_view.subviews objectAtIndex:ret];
		[view removeFromSuperview];
	}
	
	return ret;
}



void removeViewAllOnView( UIView* on_view )
{
	for( ; [on_view.subviews count] > 0; )
	{
		UIView *view = [on_view.subviews objectAtIndex:0];
		[view removeFromSuperview];
	}
}



void replaceViewAnimation(UIView* on_view, UIView* new_view, UIView* old_view, ReplaceAnimation* anim)
{
	[anim setAnimation:on_view];
	replaceView(on_view, new_view, old_view);
}


void replaceView( UIView* on_view, UIView* new_view, UIView* old_view )
{	
	
	int old_view_idx = removeViewOnView( on_view, old_view );
	if( old_view_idx >= 0 )
	{
		
		[on_view insertSubview:new_view atIndex:old_view_idx];
	}
	else
	{
		
		[on_view addSubview:new_view];
	}
}



void replaceViewCAAnim( UIView* on_view, UIView* new_view, UIView* old_view,
					   BOOL is_anime, NSString* anime_type, NSString* anime_subtype, CGFloat duration
)
{
	
	if( is_anime == YES )
	{
		
		setCAAnimation( on_view, anime_type, anime_subtype, duration );
	}
	
	
	replaceView( on_view, new_view, old_view );
	
}



void replaceViewUIViewAnim( UIView* on_view, UIView* new_view, UIView* old_view,
						   BOOL is_anime, UIViewAnimationTransition trans_type, CGFloat duration
)
{
	
	if( is_anime == YES )
	{
		
		setUIViewAnimation( on_view, trans_type, duration );
	}
	
	
	replaceView( on_view, new_view, old_view );
}



BOOL isDeviceLandScape( UIDeviceOrientation device_orie )
{
	return UIDeviceOrientationIsLandscape( device_orie );
}



@interface NSString(convertChr)
-(NSString*)convertChar:(NSString*)src dest:(NSString*)dest;
@end


@implementation NSString(convertChr)
-(NSString*)convertChar:(NSString*)src dest:(NSString*)dest
{
	
	return [[self componentsSeparatedByString:src] componentsJoinedByString:dest];
}
@end



NSString* convertString( NSString* base, NSString* before, NSString* after, BOOL is_loop )
{
	return [base convertChar:before dest:after];
	/*
	 NSMutableString* tmp = [NSMutableString stringWithString:base];
	 NSRange range = [tmp rangeOfString:before];
	 while( range.location != NSNotFound )
	 {
	 [tmp deleteCharactersInRange:range];
	 [tmp insertString:after atIndex:range.location];
	 
	 if( is_loop == NO ) break;
	 range = [tmp rangeOfString:before];
	 }
	 return [NSString stringWithString:tmp];
	 */
}

NSString* convertUnuseFileNameString( NSString* base, NSString* convert )
{
	static NSString* unuse_code[] =
	{
		@"¥", @"/", @":", @"*", @"?",
		@"<", @">", @"|",
		nil,
	};
	NSString* ret = [NSString stringWithString:base];
	for( int i=0; unuse_code[i]; i++ )
	{
		ret = convertString(ret, unuse_code[i], convert, YES);
	}
	return ret;
}

NSString* convertPathString( NSString* base, int num )
{
	NSArray *items = [base componentsSeparatedByString:@"."];
	
	if([items count] > num)
	{
		
		NSRange searchResult = [base rangeOfString:[items objectAtIndex:num]];
		return [base substringFromIndex:searchResult.location];
	}
	return base;
}


NSString* convertAmp2And(NSString* string)
{
	if( string != nil )
	{
		string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
	}
	return string;
}


NSString* encodeURLComponent(NSString* uri)
{
	NSString* ret = (NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
																	   (CFStringRef)uri,
																	   NULL,
																	   (CFStringRef)@";,/?:@&=+$#",
																	   kCFStringEncodingUTF8);
	return [ret autorelease];
}


UIImage* resizeImage(UIImage* src, CGSize size)
{
	
	//		http://developer.apple.com/iPhone/library/samplecode/iPhoneCoreDataRecipes/Introduction/Intro.html

	CGRect rect = CGRectMake(0, 0, size.width, size.height);
	UIGraphicsBeginImageContext(size);
	[src drawInRect:rect];
	
	UIImage* destImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
	UIGraphicsEndImageContext();
	
	
	return [destImage autorelease];
}



UIImage* captureLayer(CALayer* layer)
{
	UIImage* image = nil;
	if ( layer ) {
		UIGraphicsBeginImageContext(layer.bounds.size);
		[layer renderInContext:UIGraphicsGetCurrentContext()];
		
		image = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
	}
	return image;
}

UIImage* captureView(UIView* view)
{
	return captureLayer(view.layer);
}


BOOL movieFormat(NSString* path)
{
	NSString* suffix = [[path pathExtension] lowercaseString];
	if (( [suffix isEqualToString:@"m4v"] )
		|| ( [suffix isEqualToString:@"mov"] )
		|| ( [suffix isEqualToString:@"mp4"] ))
	{
		return YES;
	}
	return NO;
}

BOOL audioFormat(NSString* path)
{
	NSString* suffix = [[path pathExtension] lowercaseString];
	if (( [suffix isEqualToString:@"aac"] )
		|| ( [suffix isEqualToString:@"adts"] )
		|| ( [suffix isEqualToString:@"ac3"] )
		|| ( [suffix isEqualToString:@"aiff"] )
		|| ( [suffix isEqualToString:@"aifc"] )
		|| ( [suffix isEqualToString:@"caf"] )
		|| ( [suffix isEqualToString:@"mp3"] )
		|| ( [suffix isEqualToString:@"wav"] )
		|| ( [suffix isEqualToString:@"m4a"] ))
	{
		return YES;
	}
	return NO;
}
